#include "tle5012b.h"
#include "gd32f1x0_spi.h"
#include "litefoc_port.h"

u16_t SPIx_ReadWriteByte(u16_t u16RegValue)
{
	u16_t read_value = 0;
	u32_t i;

	i = 2000;
	while (spi_i2s_flag_get(SPI0, SPI_FLAG_TBE) == RESET && i--);
	spi_i2s_data_transmit(SPI0, u16RegValue);
	i = 2000;
	while (spi_i2s_flag_get(SPI0, SPI_FLAG_RBNE) == RESET && i--);
	read_value = spi_i2s_data_receive(SPI0);

	return read_value;
}
 

float ReadAngle(void)
{
	return ( ReadValue(READ_ANGLE_VALUE) * 360.0f / 0x10000 );
}
 

u16_t ReadSpeed(void)
{
	return ReadValue(READ_SPEED_VALUE);
}
 
 
u16_t ReadValue(u16_t u16RegValue)
{
	u16_t u16Data;

	// 读取 tle5012b 数据, 在一个spi通信中先发16bit命令数据然后再接收16bit数据，共发32个clk；
	// 由于 tle5012b 的输入输出共用一个引脚（DATA），需要在写指令时设置为推完输出模式，在接收数据时设置为开漏模式且输出为高。
	gpio_bit_reset(SPI_CSQ_PORT, SPI_CSQ_PIN);
	gpio_output_options_set(SPI_MOSI_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, SPI_MOSI_PIN);
	SPIx_ReadWriteByte(u16RegValue);
	gpio_output_options_set(SPI_MOSI_PORT, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ, SPI_MOSI_PIN);
	u16Data = SPIx_ReadWriteByte(0xffff);
	gpio_bit_set(SPI_CSQ_PORT, SPI_CSQ_PIN);

	return((u16Data & 0x7FFF) << 1);
}



